﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;

namespace OmniKits.Windows.Converters
{
    public class DoubleToThicknessConverter : IValueConverter
    {
        private static readonly ThicknessConverter ThicknessConverter = new ThicknessConverter();

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var tm = value as double?;
            if (tm == null)
                return DependencyProperty.UnsetValue;

            var tt = parameter as Thickness?;
            Thickness t;
            if (tt != null)
                t = tt.Value;
            else
            {
                try
                {
                    t = (Thickness)ThicknessConverter.ConvertFromInvariantString(parameter as string);
                }
                catch
                {
                    return DependencyProperty.UnsetValue;
                }
            }

            var m = tm.Value;
            return new Thickness(t.Left * m, t.Top * m, t.Right * m, t.Bottom * m);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var tm = value as double?;
            if (tm == null)
                return DependencyProperty.UnsetValue;

            var tt = parameter as Thickness?;
            Thickness t;
            if (tt != null)
                t = tt.Value;
            else
            {
                try
                {
                    t = (Thickness)ThicknessConverter.ConvertFromInvariantString(parameter as string);
                }
                catch
                {
                    return DependencyProperty.UnsetValue;
                }
            }

            var m = tm.Value;
            return new Thickness(t.Left / m, t.Top / m, t.Right / m, t.Bottom / m);
        }
    }
}
